/*
 * WapLoginInterceptor.java
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package cn.org.itool.web.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.org.itool.common.component.AESComponent;
import cn.org.itool.web.template.WebLoginTemplate;
import cn.org.itool.web.util.RequestAttrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

/**
 * 描述:
 *
 * @author wangbei
 */
@Log4j2
@Component
public class WapLoginInterceptor extends TrackableInterceptor {

    @Resource
    private AESComponent aesComponent;

    @Resource
    private WebLoginTemplate webLoginComponent;

    @Value("${i-tool.auth.head-token-name}")
    private String headTokenName;


    @Override
    public boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!isAfterInterceptor(request, PreLoginInterceptor.class)) {
            log.error("必须先配置以下拦截器 {} on {}", PreLoginInterceptor.class.getName(), request.getRequestURI());
        }

        // 获取token
        String token = request.getHeader(headTokenName);

        log.info("head token: {}", token);

        if(StrUtil.isNotBlank(token)) {
            String userId = webLoginComponent.getUserIdByToken(token);
            if(StrUtil.isNotBlank(userId)) {
                RequestAttrUtil.setUserIdFromRequest(userId);
                RequestAttrUtil.setTokenFromRequest(token);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){

    }


}

